package com.taobao.system.controller;
import com.taobao.basic.util.JsonResult;

import com.taobao.basic.util.PageList;
import com.taobao.system.domain.Menu;
import com.taobao.system.query.MenuQuery;
import com.taobao.system.service.IMenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController // controller层，返回json格式数据
@RequestMapping("/menu")
@Api(value = "权限接口类",description = "权限接口的CRUD操作")
public class MenuController {

    @Autowired
    private IMenuService menuService;

   /**
     * 获取权限树
     * @return
     */
    @GetMapping("/menuTree")
    public  List<Menu> menuTree(){
        return menuService.menuTree();
    };

    /**
     * 查询所有数据
     * @return
     */
    @GetMapping
    @ApiOperation(value = "查询所有")
    public List<Menu> findAll(){
        return menuService.loadAll();
    }
    /**
     * 根据id查询单个数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "查询单个对象")
    public Menu findOne(@PathVariable("id") Long id){
        return menuService.loadById(id);
    };
    /**
     * 删除操作
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除接口")
    public JsonResult DeleteByID(@PathVariable("id") Long id){
        try {
            menuService.remove(id);
            return JsonResult.me();
        }catch (Exception e){
            e.printStackTrace();
            return  JsonResult.me().setMsg("网络加载失败，请稍后重试！！");
        }
    }
    /**
     * 添加或修改操作
     * @param menu
     * @return
     */
    @PutMapping
    @ApiOperation(value = "添加或修改接口")
    public JsonResult updateOrAdd(@RequestBody Menu menu ){
        try {
            if (menu.getId() == null){
                menuService.save(menu);
            }else {
                menuService.update(menu);
            }
            return JsonResult.me();
        }catch (Exception e){
            e.printStackTrace();
            return JsonResult.me().setMsg("操作失败");
        }
    }

    /**
     * 分页查询
     * @param query
     * @return
     *
     */
    @PostMapping
    @ApiOperation(value = "分页查询接口")
    // @RequestBody -从请求体中获取数据赋值给menuQuery
    public PageList<Menu> pageQuery(@RequestBody MenuQuery query){
        try {
            return menuService.pageQuery(query);
        }catch (Exception e){
            e.printStackTrace();
            return new PageList<Menu>();
        }
    }
    /**
     * 批量删除
     * @param ids
     * @return
    */
    @PatchMapping()
    @ApiOperation(value = "删除接口")
    public JsonResult patchDel(@RequestBody List<Long> ids){
        try {
            menuService.patchDel(ids);
            return JsonResult.me();
        }catch (Exception e){
            e.printStackTrace();
            return  JsonResult.me().setMsg("网络加载失败，请稍后重试！！");
        }
    }
}
